
/* to be used in conjunction with Program 3-2 */

void keypad_init(void);
unsigned char keypad_kbhit(void);

int main(void)
{
    unsigned char key;
    
    keypad_init();
    LCD_init();

    while(1)
    {
        LCD_command(0x80);      /* LCD cursor location */
        
        if (keypad_kbhit() != 0) /* if a key is pressed */
            LCD_data('P');      /* display 'P' */
        else
            LCD_data('R');      /* display 'R' */

        delayMs(10);        /* wait for a while */
    }
}

#define KEYPAD_ROW GPIOE
#define KEYPAD_COL GPIOC 

/* this function initializes the ports connected to the keypad */
void keypad_init(void)
{
    SYSCTL->RCGCGPIO |= 0x04;   /* enable clock to GPIOC */
    SYSCTL->RCGCGPIO |= 0x10;   /* enable clock to GPIOE */
    
    KEYPAD_ROW->DIR |= 0x0F;     /* set row pins 3-0 as output */
    KEYPAD_ROW->DEN |= 0x0F;     /* set row pins 3-0 as digital pins */
    KEYPAD_ROW->ODR |= 0x0F;     /* set row pins 3-0 as open drain */
    
    KEYPAD_COL->DIR &= ~0xF0;    /* set column pin 7-4 as input */
    KEYPAD_COL->DEN |= 0xF0;     /* set column pin 7-4 as digital pins */
    KEYPAD_COL->PUR |= 0xF0;     /* enable pull-ups for pin 7-4
}

/* This is a non-blocking function. */
/* If a key is pressed, it returns 1. */
/* Otherwise, it returns a 0 (not ASCII 0).*/
unsigned char keypad_kbhit(void)
{
   int col;

    /* check to see any key pressed */
    KEYPAD_ROW->DATA = 0;               /* enable all rows */
    col = KEYPAD_COL->DATA & 0xF0;      /* read all columns */
    if (col == 0xF0) 
        return 0;   /* no key pressed */
    else
        return 1;   /* a key is pressed */
}